<template>
  <div>
    <form-view class="task-tab-container task-view-containner bbx-cell-form-view" :class="formCellCount > 1 ? 'bbx-task-tab-container-cell' : ''" :fields="taskfields" :value="task" :form-cell-count="formCellCount">
      <template slot="taskNo" slot-scope="{ field, value }">
        <!-- start 工单编号 -->
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">{{ value }}</div>
        </div>
        <!-- end 工单编号 -->

        <!-- start 工单类型 -->
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ $t('common.task.taskType') }}</label>
          <div class="form-view-row-content">{{ task.templateName }}</div>
        </div>
        <!-- end 工单编号 -->
      </template>

      <template slot="customer" slot-scope="{ field }">
        <!-- start 客户信息 -->
        <div class="form-view-row bbx-form-cell-item bbx-form-cell-item-margin">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content customer-info-wrap">
            <span :class="['customer-name', { 'link-text': allowOpenCustomerView }]" @click="openCustomerView(false)">
              {{ task.customer.name }}
            </span>
            <el-tooltip v-if="showCustomerRelationTaskCount" placement="top">
              <div slot="content" v-html="`${$t('task.unfinishedTask')}：${customerRelationTaskCountData.unfinished} </br> ${$t('task.allTask')}：${customerRelationTaskCountData.all}`"></div>
              <div class="relation-count-button" @click="openCustomerView(true)" v-track="$track.formatParams('CHECK_CUSTOMER_TASK_NUM')">
                {{ `${customerRelationTaskCountData.unfinished}/${customerRelationTaskCountData.all}` }}
              </div>
            </el-tooltip>
            <el-tooltip v-if="task.customer && task.customer.tenantTagList && task.customer.tenantTagList.length" placement="top">
              <div slot="content">
                {{ customerTagValue(task.customer.tenantTagList) }}
              </div>
              <base-tags :value="customerLabel(task.customer.tenantTagList)" />
            </el-tooltip>
          </div>
        </div>
        <!-- end 客户信息 -->
        <!-- start 联系人信息 -->
        <div class="form-view-row linkman-name bbx-form-cell-item" v-if="customerOption.linkman">
          <label>{{ $t('common.base.contact') }}</label>
          <div class="form-view-row-content">{{ lmName }}</div>
        </div>
        <div class="form-view-row linkman-phone bbx-form-cell-item" v-if="customerOption.linkman">
          <label>{{ $t('common.base.phone') }}</label>
          <div class="form-view-row-content call-phone">
            <span>{{ lmPhone }}</span>
            <biz-call-icon :value="lmPhone" :sourceData="callCenterSourceData" />
          </div>
        </div>
        <div class="form-view-row address-info bbx-form-cell-item bbx-form-cell-item-margin" v-if="customerOption.address">
          <label>{{ $t('common.base.address') }}</label>
          <div class="form-view-row-content" @click="openMap" v-if="address">
            <el-tooltip effect="dark" :content="address" placement="top">
              <span class="address-info-content">
                <i v-if="showMap" class="iconfont icon-address"></i>
                <span>{{ address }}</span>
              </span>
            </el-tooltip>
          </div>
        </div>
        <!-- end 联系人信息 -->

        <!-- start 产品 -->
        <template v-if="customerOption.product">
          <div class="product-list form-view-row bbx-form-cell-item bbx-form-cell-item-margin" v-if="!products.length">
            <label>{{ $t('common.base.product') }}</label>
          </div>
          <div class="product-list bbx-form-item bbx-form-cell-item-margin" v-else>
            <div class="product-item" v-for="(product, index) in products" :key="product.id">
              <div class="product-item-name">
                <label>{{ $t('common.base.product') }}</label>
                <span class="link-text" :key="product.id" @click="openProductView(product.id)" v-if="!isEncryptField(product.name) && canSeeCustomer">{{ product.name }}</span>
                <span v-else>{{ product.name }}</span>
                <el-tooltip v-if="showProductRelationCount(product) && canSeeCustomer" placement="top">
                  <div slot="content" v-html="$t('task.detail.components.unfinishedAndAllTask', { unfinished: productRelationCount[product.id].unfinished, all: productRelationCount[product.id].all})"></div>
                  <div class="relation-count-button" @click="openProductView(product.id)">
                    {{ `${productRelationCount[product.id].unfinished}/${productRelationCount[product.id].all}` }}
                  </div>
                </el-tooltip>
              </div>
              <div class="form-row-two-columns product-item-relation bbx-form-item bbx-form-cell-item-margin" v-if="relationProductfields.length">
                <div class="form-view-row" v-for="field in relationProductfields" :key="field.id">
                  <label>{{ field.displayName }}</label>
                  <!-- 多级菜单多选 -->
                  <div v-if="(field.setting || {}).formType === 'cascader' && (field.setting || {}).isMulti" class="form-view-row-content">
                    {{ (task.attribute[field.fieldName] || [])[index] | fmt_form_cascader((field.setting || {}).isMulti, (field.setting || {}).displayMode) }}
                  </div>
                  <div class="form-view-row-content" v-else>
                    <span v-if="['date', 'datetime'].includes(field.setting.formType)">
                      {{ disposeFormItemViewTime(field, prettyRelationProductValue(task.attribute[field.fieldName], index)) }}
                    </span>
                    <span v-else>{{ prettyRelationProductValue(task.attribute[field.fieldName], index) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <!-- end 产品 -->

        <!-- TODO: 临时解决客户字段设置产品未勾选时隐藏 -->
        <template v-else><div class="hide"></div></template>
      </template>

      <!-- start 是否重复报修 -->
      <template slot="isRepeatRepair" slot-scope="{ field }" v-if="field.fieldName == 'isRepeatRepair'">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ $t('task.detail.components.isRepeatRepair') }}</label>
          <div class="form-view-row-content" :style="{ color: field.setting.color || '#F4882F' }">{{ task.attribute[field.fieldName] || $t('common.base.no') }}</div>
        </div>
      </template>
      <!-- end 是否重复报修 -->

      <!-- start 计划时间 -->
      <template slot="planTime" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content form-view-row-plantime">
            {{ planTime }}
            <template v-if="allowModifyPlanTime">
              <el-tooltip class="item" effect="dark" :content="$t('task.modifyPlanTime')" placement="top">
                <i class="iconfont icon-bianji1" @click="modifyPlanTime"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 计划时间 -->

      <!-- start 计划开始时间 -->
      <template slot="planStartTime" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content form-view-row-plantime">
            <bbx-timezone-time-picker :field="field" :value="planStartTime"></bbx-timezone-time-picker>
            <!-- {{ planStartTime }} -->
            <template v-if="allowModifyPlanTime">
              <el-tooltip class="item" effect="dark" :content="$t('task.modifyPlanStartTime')" placement="top">
                <i class="iconfont icon-bianji1" @click="modifyPlanTime('modifyCalendarPlanTime')"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 计划开始时间 -->

      <!-- start 计划完成时间 -->
      <template slot="planEndTime" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content form-view-row-plantime">
            <bbx-timezone-time-picker :field="field" :value="planEndTime"></bbx-timezone-time-picker>
            <template v-if="allowModifyPlanTime">
              <el-tooltip class="item" effect="dark" :content="$t('task.modifyPlanEndTime')" placement="top">
                <i class="iconfont icon-bianji1" @click="modifyPlanTime('modifyCalendarPlanTime')"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 计划完成时间 -->

      <!-- start 计划开始和结束时间 -->
      <template slot="calendarPlanTime" slot-scope="scope"  v-if="!calendarPlanTime">
        <div class="form-calendar-time bbx-form-item bbx-form-cell-item-margin bbx-task-planTime-view bbx-form-item-view-no-margin" >
          <div class="form-view-row bbx-form-cell-item">
            <label>{{ $t('common.form.type.planStartTime') }}</label>
            <div class="form-view-row-content form-view-row-plantime">
              <bbx-timezone-time-picker :value="planStartTime"></bbx-timezone-time-picker>
            </div>
          </div>

          <div class="form-view-row bbx-form-cell-item">
            <label>{{ $t('common.form.type.planEndTime') }}</label>
            <div class="form-view-row-content form-view-row-plantime">
              <bbx-timezone-time-picker :value="planEndTime"></bbx-timezone-time-picker>
            </div>
          </div>
        </div>

        <template v-if="allowModifyPlanTime">
          <el-tooltip class="item" effect="dark" :content="$t('task.modifyPlanTime')" placement="top">
            <i class="iconfont icon-bianji1" @click="modifyPlanTime('modifyCalendarPlanTime')"></i>
          </el-tooltip>
        </template>
      </template>
      <!-- end 计划开始和结束时间 -->

      <!-- start 完成时间 -->
      <template slot="completeTime" slot-scope="{ field }" v-if="finishedState">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">{{ task.completeTime | fmt_datetime }}</div>
        </div>
      </template>
      <!-- end 完成时间 -->

      <!-- start 满意度 -->
      <template slot="degree" slot-scope="{ field }" v-if="task.isReview == 1">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">{{ task.degree }}</div>
        </div>
      </template>
      <!-- end 满意度 -->

      <!-- start 工单状态 -->
      <template slot="state" slot-scope="{ field }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <div class="task-state" :style="{ 'background-color': stateColor.bgColor, 'color': '#FFF' }">{{ stateText }}</div>
          </div>
        </div>
      </template>
      <!-- end 工单状态 -->

      <!-- start 创建人 -->
      <template slot="createUser" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div v-if="value" class="form-view-row-content">
            <span v-user="value.userId" class="user-card-triggle">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="value.staffId"></open-data>
              </template>
              <template v-else>
                {{ value.displayName }}
              </template>
            </span>
            <template v-if="isProviderManager && task.serviceProviderCreateName">
              <span>（{{ task.serviceProviderCreateName }}）</span>
            </template>
          </div>
        </div>
      </template>
      <!-- end 创建人 -->
      <!-- start 负责人 -->
      <template slot="executor" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div v-if="value" class="form-view-row-content">
            <span v-user="value.userId" class="user-card-triggle">
              <template v-if="isOpenData">
                <open-data type="userName" :openid="value.staffId"></open-data>
              </template>
              <template v-else>
                {{ value.displayName }}
              </template>
            </span>
            <template v-if="isProviderManager && task.serviceProviderName">
              <span>（{{ task.serviceProviderName }}）</span>
            </template>
          </div>
        </div>
      </template>
      <!-- end 负责人 -->
      <!-- start 派单人 -->
      <template slot="allotUser" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div v-if="value" class="form-view-row-content">
            <template v-if="isOpenData">
              <open-data type="userName" :openid="value.staffId"></open-data>
            </template>
            <template v-else>
              {{ value.displayName }}
            </template>
          </div>
        </div>
      </template>
      <!-- end 派单人 -->
      <!-- start 协同人 -->
      <template slot="synergies" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <template v-if="isOpenData && value">
              <span v-for="item in value" v-user="item.userId" :key="item.userId" class="user-card-triggle">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </span>
            </template>
            <template v-else>
              <span class="synergies-name user-card-triggle" v-for="item in value" :key="item.userId" v-user="item.userId">{{ item.displayName }}</span>
            </template>
            <template v-if="allowEditSynergy">
              <el-tooltip class="item" effect="dark" :content="$t('customer.detail.customerDetailFormView.modifySynergiesTooltip')" placement="top">
                <i class="iconfont icon-bianji1" @click="modifySynergies"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 协同人 -->
      <!-- start 节点负责人 -->
      <template slot="currentNodeExecutor" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            <template v-if="isOpenData && value">
              <span v-for="item in value" v-user="item.userId" :key="item.userId" class="user-card-triggle">
                <open-data type="userName" :openid="item.staffId"></open-data>
              </span>
            </template>
            <template v-else>
              <span class="synergies-name user-card-triggle" v-for="item in value" :key="item.userId" v-user="item.userId">{{ item.displayName }}</span>
            </template>
            <template v-if="allowModifyCustomExecutor">
              <el-tooltip class="item" effect="dark" :content="$t('common.task.modifyCustomNodeUSer', {nodeName: field.displayName})" placement="top">
                <i class="iconfont icon-bianji1" @click="modifyCustomNodeLeader(field.displayName)"></i>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
      <!-- end 节点负责人 -->
      <!-- 创建方式 -->
      <template slot="source" slot-scope="{ field }" v-if="task.source">
        <div class="form-view-row bbx-form-cell-item">
          <label>{{ field.displayName }}</label>
          <div class="form-view-row-content">
            {{ getSoureceLabel(task.source) }}
            <a class="link-text" :href="`${$resourcePrefix}/event/view/${task.eventId}`" v-if="!isBasicEditionHideEvent">
              <template v-if="task.eventNo"> #{{ task.eventNo }} </template>
            </a>
            <div style="display: inline-block" v-else>
              <template v-if="task.eventNo"> #{{ task.eventNo }} </template>
            </div>
          </div>
        </div>
      </template>
      <!-- end 创建方式 -->

      <!-- start 故障库 -->
      <template slot="faultLibrary" slot-scope="{ field, value }">
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.productType">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel1') }}</label>
          <div class="form-view-row-content">{{ value.productType }}</div>
        </div>
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.faultScene">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel2') }}</label>
          <div class="form-view-row-content">{{ value.faultScene }}</div>
        </div>
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.faultDetails">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel3') }}</label>
          <div class="form-view-row-content">{{ value.faultDetails }}</div>
        </div>
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.faultReason">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel4') }}</label>
          <div class="form-view-row-content">{{ value.faultReason }}</div>
        </div>
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.budgetAmount">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel6') }}</label>
          <div class="form-view-row-content">
            <template v-if="budgetAmountMax && budgetAmountMin"> {{ budgetAmountMin }} ～ {{ budgetAmountMax }} </template>
            <template v-else-if="budgetAmountMax">
              {{ budgetAmountMax }}
            </template>
            <template v-else-if="budgetAmountMin">
              {{ budgetAmountMin }}
            </template>
          </div>
        </div>
        <div class="form-view-row bbx-form-cell-item" v-if="faultLibraryOption.solution && showSolution">
          <label>{{ $t('common.form.preview.faultLibrary.concatLabel5') }}</label>
          <div class="form-view-row-content">
            <span class="link-text" @click="openKnowledgeView(value.wikiId)">{{ $t('task.detail.components.viewSolution') }}</span>
          </div>
        </div>
      </template>
      <!-- end 故障库 -->
    </form-view>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import BbxTimezoneTimePicker from '@src/component/Bbx/TimezoneTimePicker';
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';

/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
import { TaskCreateMethodLabelEnum } from '@model/enum/LabelEnum.ts';
import { isBasicEditionHideEvent } from '@shb-lib/version';
import { getCount } from '@src/api/ArchiveApi';
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum';
import { chooseExUser } from '@model/config/SelectUserConfig.ts';
import { getRootWindow } from '@src/util/dom';
import { openTabForProductView, openTabForEventView } from '@src/util/business/openTab';

import { formatDate, useFormTimezone, clearObject } from 'pub-bbx-utils';
import i18n from '@src/locales';

import { customerTagValue, customerLabel } from '@src/modules/customer/util/customer.js';

const { disposeFormItemViewTime } = useFormTimezone();

const ENCRYPT_FIELD_VALUE = '***';

export default {
  name: 'task-view',
  components: {
    BbxTimezoneTimePicker,
    FormCellChange,
  },
  props: {
    task: {
      type: Object,
      default: () => ({}),
    },
    fields: {
      type: Array,
      default: () => [],
    },
    finishedState: {
      type: Boolean,
      default: false,
    },
    allowModifyPlanTime: {
      type: Boolean,
      default: false,
    },
    isPaused: {
      type: Boolean,
      default: false,
    },
    canSeeCustomer: {
      type: Boolean,
      default: false,
    },
    allowEditSynergy: {
      type: Boolean,
      default: false,
    },
    allowModifyCustomExecutor: {
      type: Boolean,
      default: false,
    },
    customerOption: {
      type: Object,
      default: () => ({}),
    },
    allowOpenCustomerView: {
      type: Boolean,
      default: false,
    },
    showCustomerRelationTaskCount: {
      type: Boolean,
      default: false,
    },
    customerRelationTaskCountData: {
      type: Object,
      default: () => ({}),
    },
    lmName: {
      type: String,
      default: '',
    },
    lmPhone: {
      type: String,
      default: '',
    },
    address: {
      type: String,
      default: '',
    },
    showMap: {
      type: Boolean,
      default: false,
    },
    showCallPhone: {
      type: Boolean,
      default: false,
    },
    planTime: {
      type: [String, Number],
      default: '',
    },
    planStartTime: {
      type: [String, Number],
      default: '',
    },
    planEndTime: {
      type: [String, Number],
      default: '',
    },
    stateColor: {
      type: Object,
      default: () => ({}),
    },
    stateText: {
      type: String,
      default: '',
    },
    calendarPlanTime: {
      type: Boolean,
      default: false,
    },
    formCellCount:{
      type: Number,
      default: 1
    },
    intelligentConfig: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      isOpenData,
      products: this.buildProducts(),
      productRelationCount: {}, // 产品关联的工单数量
      archiveCountArr: [], // 归档工单数量
    };
  },
  computed: {
    qualityStartTime() {
      return (this.task?.qualityInfo?.qualityStartTime && formatDate(this.task?.qualityInfo?.qualityStartTime, 'date')) || '';
    },
    qualityEndTime() {
      return (this.task?.qualityInfo?.qualityEndTime && formatDate(this.task?.qualityInfo?.qualityEndTime, 'date')) || '';
    },
    qualityStatus() {
      return this.task?.qualityInfo?.qualityStatus || '';
    },
    /**
     * @description 工单自定义字段
     * 过滤产品关联字段，需给每个产品显示对应产品关联字段
     */
    taskfields() {
      return this.fields.filter(field => field.formType != 'relationProduct');
    },
    /**
     * @description 产品关联字段
     */
    relationProductfields() {
      return this.fields.filter(field => field.formType == 'relationProduct');
    },
    // 基础版功能隐藏事件
    isBasicEditionHideEvent() {
      return isBasicEditionHideEvent();
    },
    /**
     * @description 故障库字段配置
     */
    faultLibraryField() {
      const faultLibrary = this.fields.filter(f => f.fieldName === 'faultLibrary');
      return faultLibrary ? faultLibrary[0] : {};
    },
    faultLibraryOption() {
      return (this.faultLibraryField?.setting && this.faultLibraryField.setting.faultLibraryOption) || {};
    },
    budgetAmountMin() {
      let budgetAmountMin = this.task?.faultLibrary?.budgetAmountMin;
      if (budgetAmountMin != null) {
        return Number(budgetAmountMin).toFixed(2);
      }
      return budgetAmountMin;
    },
    budgetAmountMax() {
      let budgetAmountMax = this.task?.faultLibrary?.budgetAmountMax;
      if (budgetAmountMax != null) {
        return Number(budgetAmountMax).toFixed(2);
      }
      return budgetAmountMax;
    },
    /**
     * @description 显示解决方案
     */
    showSolution() {
      return !!(this.task?.faultLibrary?.wikiId != -1 && this.task?.faultLibrary?.faultScene);
    },
    // 是否开启服务商灰度
    isProviderManager() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.providerManager || false;
    },
    // 呼叫中心来源数据
    callCenterSourceData() {
      return {
        sourceTypeId: this.task.id,
        sourceType: 'task',
        sourceTypeNo: this.task.taskNo,
      };
    },
  },
  filters: {
    filterQualityStatus(value) {
      if (value) {
        return value == 'OUT' || value == '保外' ? i18n.t('common.base.surrender') : i18n.t('common.base.warranty');
      }
      return '';
    },
  },
  methods: {
    disposeFormItemViewTime,
    // 获取归档工单数量
    getCount() {
      this.products.forEach(async (product, index) => {
        let params = {
          productId: product.id,
        };
        let { code, message, result } = await getCount(params);
        if (code === 0) {
          this.archiveCountArr[index] = result.archiveCount;
        } else {
          this.$notify({
            title: this.$t('common.base.fail'),
            message,
            type: 'error',
          });
        }
      });
    },
    /**
     * @description 打开事件详情
     */
    openEventView(id) {
      openTabForEventView(id);
    },
    /**
     * @description 修改计划时间
     */
    modifyPlanTime(type) {
      this.$emit('modifyPlanTime', type);
    },
    makePhoneCall() {
      this.$emit('makePhoneCall');
    },
    openMap() {
      this.$emit('openMap');
    },
    openCustomerView(openTaskTab) {
      this.$emit('openCustomerView', openTaskTab);
    },
    /**
     * @description 打开产品详情
     */
    openProductView(productId) {
      this.$track.clickStat(this.$track.formatParams('CHECK_PRODUCT_TASK_NUM'));

      openTabForProductView(productId);
    },
    /**
     * @description 获取关联的工单数量
     */
    getCountForCreate(params) {
      return TaskApi.getCountForCreate(params).then((result = {}) => {
        this.$set(this.productRelationCount, params.id, result);
      });
    },
    /**
     * @description 是否显示产品关联的工单数量
     * 1. 全部数量>0
     * 2. 且未加密
     */
    showProductRelationCount(product) {
      let { id, name } = product;
      let { all } = this.productRelationCount[id] || {};
      return (Number(all) > 0 && !this.isEncryptField(name)) || this.archiveCountArr.length > 0;
    },
    /**
     * @description 是否加密字段
     */
    isEncryptField(value) {
      return value === ENCRYPT_FIELD_VALUE;
    },
    /**
     * @description 产品
     */
    buildProducts() {
      let productsArr = [];
      let { products, product } = this.task;

      if (products && products.length) return products;
      if (product && product.id) return productsArr.push(product);

      return productsArr;
    },
    /**
     * @description 修改协同人
     */
    modifySynergies() {
      console.log(this.task.synergies, 'this.task.synergies');
      let options = {
        title: this.$t('customer.detail.customerDetailFormView.modifySynergiesTooltip'),
        max: 100,
        selectedUsers: this.task.synergies,
        ...chooseExUser,
        mode: BaseSelectUserModeEnum.Filter,
      };

      return this.$fast.select.multi
        .all(options)
        .then(result => {
          if (result.status == 0) {
            let synergies = result?.data?.users || [];

            const params = { taskId: this.task.id, synergies };
            TaskApi.updateSynergies(params)
              .then(res => {
                if (res.success) {
                  this.task.synergies = synergies;

                  this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
                } else {
                  this.$platform.alert(res.message);
                }
              })
              .catch(err => console.error(err));
          }
        })
        .catch(err => console.error(err));
    },
    /**
     * @description 修改节点负责人
     */
    modifyCustomNodeLeader(nodeName) {
      let options = {
        title: this.$t('common.task.modifyCustomNodeUSer', {nodeName}),
        max: 100,
        selectedUsers: this.task.currentNodeExecutor,
        ...chooseExUser,
        mode: BaseSelectUserModeEnum.Filter,
      };

      return this.$fast.select.multi
          .all(options)
          .then(result => {
            if (result.status == 0) {
              const users = result?.data?.users || [];
              const userIdList = users?.map(item => item.userId)

              const params = { taskId: this.task.id, userIdList };
              TaskApi.updateCurrentNodeExecutor(params)
                  .then(res => {
                    if (res.success) {
                      this.task.currentNodeExecutor = users;

                      this.$message.success(this.$t('common.task.modifyCustomUser'))

                      this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord);
                    } else {
                      this.$platform.alert(res.message);
                    }
                  })
                  .catch(err => console.error(err));
            }
          })
          .catch(err => console.error(err));
    },
    /**
     * @description 处理产品关联字段数据
     */
    prettyRelationProductValue(value, index) {
      if (Array.isArray(value)) {
        return value[index];
      }

      return value;
    },
    /**
     * @description 打开知识库详情
     */
    openKnowledgeView(wikiId) {
      let fromId = window.frameElement.getAttribute('id');

      if (!wikiId) return;

      openAccurateTab({
        type: PageRoutesTypeEnum.PageWikiDetail,
        key: wikiId,
        params: `wikiId=${wikiId}`,
        fromId,
      });
    },
    // 获取创建方式的多语言label
    getSoureceLabel(key) {
      return TaskCreateMethodLabelEnum[key] || key;
    },
    customerTagValue,
    customerLabel,
  },
  created() {
    // 查询产品关联工单数量
    if (this.canSeeCustomer) {
      this.products.map(item => {
        this.$set(this.productRelationCount, item.id, { all: 0, unfinished: 0 });
        this.getCountForCreate({ module: 'product', id: item.id });
      });
    }
    // 去除相关获取getCount的接口
    // this.getCount();
  },
};
</script>
<style lang="scss">
.task-view-containner {
  .form-view-row-plantime {
    white-space: nowrap;
  }

  .icon-bianji1 {
    font-size: 14px;
  }

  .customer-info-wrap {
    display: flex;
    word-break: initial;
    .customer-name {
      @include text-ellipsis();
    }
  }

  .product-list {
    .product-item {
      &-name {
        line-height: 20px;
        display: flex;
        align-items: baseline;
        padding-left: 12px;
        label {
          width: 98px;
          margin-bottom: 0;
          margin-right: 10px;
          // padding-left: 20px;
          color: $text-color-regular;
          // background: url(../../../../assets/img/task/product_icon.png) no-repeat left 4px;
          background-size: 12px;
        }

        span {
          margin-right: 0;
        }
      }

      &-relation {
        width:  auto;
        margin-top: 8px;
        // padding: 6px 10px 6px 12px;
        // background-color: $bg-color-l3;
        // border-radius: $border-radius-base;
        margin-left: 108px;
        background-color: #F7F8F8;
        border-radius: 4px;
        .form-view {
          // background-color: $bg-color-l3;
        }
      }
      .product-item-name  {
        padding-left: 12px;
        label {
          &::after {
            content: ":";
            position: relative;
            top: -0.5px;
            margin: 0 8px 0 2px;
          }
        }
      }
      &:not(:last-child) {
        .product-item-name {
          margin-bottom: 8px;
        }

        .product-item-relation {
          margin-bottom: 16px;
        }
      }
    }
  }

  .synergies-name {
    margin-right: 12px;
  }
  .form-calendar-time {
    // display: flex;
    // align-items: center;
    > div {
      margin-right: 5px;
    }
    .iconfont {
      color: $color-primary;
    }
  }
}
</style>
<style lang="scss" scoped>
.address-info {
  &-content {
    display: inline-block;
    cursor: pointer;
    &:hover {
      color: $color-primary-light-6;
    }
  }
}
</style>
